// const app = require('express')()

//导入uuid模块
const uuid = require('node-uuid')

//导入数据库操作模块
const db = require("../../db/index.js")

// 格式化时间
var moment = require('moment')

/**
 * 获取公告列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getNoticeList = async (req, res) => {
    let sql = ''
    let department = req.query.department
    let title = req.query.title
    let size = parseInt(req.query.limit)
    let start = (parseInt(req.query.page) - 1) * size
    let sqlArr = []
    if (!title || title == "") {
        if (!department || department == "" || department + "" == "全部") {
            sql = `SELECT COUNT(*) FROM xks_notice WHERE flag != 0 ;
    SELECT * FROM xks_notice WHERE flag != 0 limit ?,?`;
            sqlArr = [start, size]
        }
        else {
            sql = `SELECT COUNT(*) FROM xks_notice WHERE flag != 0 AND department = ?;
    SELECT * FROM xks_notice WHERE flag != 0 AND department = ? limit ?,?`;
            sqlArr = [department, department, start, size]
        }

        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    } else {
        if (!department || department == "" || department == "全部") {
            sql = `SELECT COUNT(*) FROM xks_notice WHERE flag != 0 AND title LIKE concat('%',?, '%');
    SELECT * FROM xks_notice WHERE flag != 0 AND title LIKE concat('%',?, '%') limit ?,?`;
            sqlArr = [title, title, start, size]
        } else {
            sql = `SELECT COUNT(*) FROM xks_notice WHERE flag != 0 AND title LIKE concat('%',?, '%') AND department = ?;
    SELECT * FROM xks_notice WHERE flag != 0 AND title LIKE concat('%',?, '%') AND department = ? limit ?,?`;
            sqlArr = [title, department, title, department, start, size]
        }
        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    }
}
/**
 * 根据id获取公告详情
 * @param {*} req 
 * @param {*} res 
 */
exports.getNotice = async (req, res) => {
    const id = req.params.id
    const sql = ` SELECT * FROM xks_notice WHERE flag != 0 AND id = ?`;
    db.query(sql, id, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '错误',
                data: {}
            })
        }
        return res.send({
            code: 200,
            msg: '成功',
            data: results[0]
        })
    })
}


/**
 * 增加公告
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addNotice = (req, res) => {
    const notice = req.body;
    if (JSON.stringify(notice) == "{}") {
        console.log('【增加公告发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!notice.title || !notice.content) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    // 判断是否有操作的权限
    const admin = req.data
    if (!(notice.department + "").includes("极客")) {
        if (admin.level > '2') {
            console.log('没有权限，admin.level ===> ' + admin.level)
            return res.send({
                code: 403,
                msg: '对不起，没有权限发布该部门的内容！',
                data: {}
            })
        }
    }

    //该公告是否已存在
    const findSql = 'SELECT * FROM xks_notice WHERE flag != 0 AND title = ?'
    db.query(findSql, notice.title, (err, results) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (results.length > 0) {
            return res.send({
                code: 400,
                msg: '该公告（标题）已存在，请重新操作！',
                data: {}
            })
        }

        // //生成uuid
        // let uuid1 = uuid.v1();
        // // 去除横线-
        // uuid1 = uuid1.replace(/-/g, '');
        // // 添加id
        // notice['id'] = uuid1;

        if (!notice.publish_time) {
            //发布时间
            let nowTime = new Date()
            var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
            console.log('发布时间', formatTime)
            notice['publish_time'] = formatTime;
        } else {
            notice.publish_time = moment(notice.publish_time).format('YYYY-MM-DD HH:mm')
        }

        const addSql = `INSERT INTO xks_notice SET ? `
        db.query(addSql, notice, (err, result) => {
            if (err) {
                console.log(err.message)
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            if (result.affectedRows !== 1) {
                return res.send({
                    code: 500,
                    msg: '增加失败，请稍后再试！',
                    data: {}
                })
            }
            res.send({
                code: 200,
                msg: '增加成功',
                data: {}
            })
        })
    })
}


/**
 * 删除公告
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.delNotice = (req, res) => {

    var notice = req.params;
    if (JSON.stringify(notice) == "{}") {
        console.log('【删除学习视频发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!notice.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    const findSql = `SELECT * FROM xks_notice WHERE flag != 0 AND id = ?`;
    db.query(findSql, notice.id, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '发送了错误' + err.message,
                data: {}
            })
        }

        if (!results.length > 0) {
            return res.send({
                code: 400,
                msg: '没有找到该数据',
                data: {}
            })
        }

        notice = results[0]
        // 判断是否有操作的权限
        const admin = req.data
        if (!(notice.department + "").includes("极客")) {
            if (admin.level > '2') {
                console.log('没有权限，admin.level ===> ' + admin.level)
                return res.send({
                    code: 403,
                    msg: '对不起，没有权限删除该部门的内容！',
                    data: {}
                })
            }
        }
        console.log(notice.id)
        const delSql = `UPDATE xks_notice SET flag = 0 WHERE id = ? `
        db.query(delSql, notice.id, (err, result) => {
            if (err) {
                console.log(err.message)
                return res.send({
                    code: 505,
                    msg: err.message,
                    data: {}
                })
            }
            if (result.affectedRows !== 1) {
                return res.send({
                    code: 500,
                    msg: '删除失败，请检查ID是否有误！',
                    data: {}
                })
            }
            res.send({
                code: 200,
                msg: '删除成功！',
                data: {}
            })
        })
    })
}


/**
 * 更新公告
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateNotice = (req, res) => {
    const notice = req.body;
    if (JSON.stringify(notice) == "{}") {
        console.log('【更新学习视频发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!notice.title || !notice.content || !notice.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }


    // 判断是否有操作的权限
    const admin = req.data
    if (!(notice.department + "").includes("极客")) {
        if (admin.level > '2') {
            console.log('没有权限，admin.level ===> ' + admin.level)
            return res.send({
                code: 403,
                msg: '对不起，没有权限修改该部门的内容！',
                data: {}
            })
        }
    }

    //记录id的值
    const noticeId = notice.id
    delete notice.id

    var formatTime = moment(notice.publish_time).format('YYYY-MM-DD HH:mm')
    notice.publish_time = formatTime;

    const updateSql = `UPDATE xks_notice SET ? WHERE flag != 0 AND id = ?`
    db.query(updateSql, [notice, noticeId], (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '更新成功',
            data: {}
        })
    })
}